package com.engine.wei.base.utils.log;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.engine.wei.base.BuildConfig;
import com.engine.wei.base.utils.TimeUtils;
import com.tencent.mars.xlog.Log;
import com.tencent.mars.xlog.Xlog;

/**
 * 作者:赵若位
 * 时间:2021/7/15 10:40
 * 功能:
 */
public class LogManager {
    public static final String XLOG_DIR = "/xlog";
    public static final String CACHE_XLOG = "/cache/xlog";
    private static final String LOG_FILE_PREFIX = "Default";
    private static final String LOG_FILE_POSTFIX = ".xlog";
    private static volatile boolean sHasInitialized = false;

    /**
     * 加载动态库：需要确保在使用日志模块前调用
     */
    static {
        System.loadLibrary("c++_shared");
        System.loadLibrary("marsxlog");
    }

    /**
     * 初始化日志模块
     *
     * @param context 上下文信息
     */
    public static void init(Context context, String publicKey, boolean isDebugMode) {
        if (sHasInitialized) {
            return;
        }
        String namePrefix = getLogNamePrefix(context);
        if (namePrefix == null) {
            return;
        }
        String logPath = getLogPath(context);
        String cachePath = getCachePath(context);

        android.util.Log.e(BuildConfig.TAG, "初始化Xlog，日志地址" + logPath);
        android.util.Log.e(BuildConfig.TAG, "初始化Xlog，日志缓存地址" + cachePath);

        // 使用 Xlog 的时候请尽量不要使用同步模式，同步模式会直接写文件，同步模式主要为了调试环境用的。
        // 推荐的模式为异步模式，INFO级别。
        Xlog log = new Xlog();
        Log.setLogImp(log);
        if (isDebugMode) {
            Log.setConsoleLogOpen(true);
            log.appenderOpen(Xlog.LEVEL_VERBOSE, Xlog.AppednerModeSync, cachePath, logPath,
                    namePrefix, 0);
        } else {
            Log.setConsoleLogOpen(false);
            log.appenderOpen(Xlog.LEVEL_INFO, Xlog.AppednerModeAsync, cachePath, logPath,
                    namePrefix, 0);
        }
        sHasInitialized = true;
    }

    @Nullable
    public static String getLogNamePrefix(Context context) {
        String processName = null;
        int pid = android.os.Process.myPid();
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (am != null) {
            for (ActivityManager.RunningAppProcessInfo appProcess : am.getRunningAppProcesses()) {
                if (appProcess.pid == pid) {
                    processName = appProcess.processName;
                    break;
                }
            }
        }

        if (!TextUtils.isEmpty(processName)) {
            return !processName.contains(":")
                    ? LOG_FILE_PREFIX
                    : (LOG_FILE_PREFIX + "_" + processName.substring(processName.indexOf(":") + 1));
        }

        return null;
    }

    public static String getLogPath(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
                    context.getPackageName();
            return sdcardPath + XLOG_DIR;
        } else {
            return context.getFilesDir() + XLOG_DIR;
        }
    }

    public static String getCachePath(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
                    context.getPackageName();
            return sdcardPath + CACHE_XLOG;
        } else {
            return context.getCacheDir() + XLOG_DIR;
        }
    }

    public static String getLogFilePath(Context context) {
        return getLogPath(context)
                + "/" + getLogFileName(context);
    }

    @NonNull
    public static String getLogFileName(Context context) {
        return getLogNamePrefix(context) + "_"
                + TimeUtils.getCurDateTime("yyyyMMdd")
                + LOG_FILE_POSTFIX;
    }

    /**
     * 反初始化日志模块
     */
    public static void close() {
        Log.appenderClose();
    }
}
